﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Xml;

namespace Wilke.SharePoint.Tools
{
    public partial class OptionsForm : Form
    {
        public OptionsForm()
        {
            InitializeComponent();
        }

        private void buttonBrowseInetPub_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = folderBrowserDialog.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                textBoxInetPubPath.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            bool suggestRestart = false;

            #region Save Configuration

            StringBuilder buffer = new StringBuilder();

            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            suggestRestart = (comboBoxSharePointVersion.Text != ConfigurationHelper.SharePointVersion);

            if (configuration.AppSettings.Settings[Constants.ConfigKeySharePointVersion] == null)
            {
                configuration.AppSettings.Settings.Add(Constants.ConfigKeySharePointVersion, comboBoxSharePointVersion.Text);
            }
            else
            {
                configuration.AppSettings.Settings[Constants.ConfigKeySharePointVersion].Value = comboBoxSharePointVersion.Text;
            }

            if (configuration.AppSettings.Settings[Constants.ConfigKeyInetPubPath] == null)
            {
                configuration.AppSettings.Settings.Add(Constants.ConfigKeyInetPubPath, textBoxInetPubPath.Text);
            }
            else
            {
                configuration.AppSettings.Settings[Constants.ConfigKeyInetPubPath].Value = textBoxInetPubPath.Text;
            }

            if (configuration.AppSettings.Settings[Constants.ConfigKeyCodeGenerationNamespace] == null)
            {
                configuration.AppSettings.Settings.Add(Constants.ConfigKeyCodeGenerationNamespace, textBoxCodeGenerationNamespace.Text);
            }
            else
            {
                configuration.AppSettings.Settings[Constants.ConfigKeyCodeGenerationNamespace].Value = textBoxCodeGenerationNamespace.Text;
            }

            if (configuration.AppSettings.Settings[Constants.ConfigKeyDefaultOwner] == null)
            {
                configuration.AppSettings.Settings.Add(Constants.ConfigKeyDefaultOwner, textBoxDefaultOwner.Text);
            }
            else
            {
                configuration.AppSettings.Settings[Constants.ConfigKeyDefaultOwner].Value = textBoxDefaultOwner.Text;
            }

            Dictionary<string, string[]> multiValueSettings = new Dictionary<string, string[]>();

            multiValueSettings.Add(Constants.ConfigKeyAutoLookupNodesToIgnore, textBoxAutoLookupNodesToIgnore.Lines);
            multiValueSettings.Add(Constants.ConfigKeyFrequentlyUsedNodeNames, textBoxFrequentlyUsedNodeNames.Lines);
            multiValueSettings.Add(Constants.ConfigKeyAutoLookupDifferentiatingAttributeNames, textBoxAttributeNames.Lines);

            foreach (KeyValuePair<string, string[]> entry in multiValueSettings)
            {
                buffer.Length = 0;

                foreach (string node in entry.Value)
                {
                    if (!String.IsNullOrEmpty(node))
                    {
                        buffer.Append(node);
                        buffer.Append("|");
                    }
                }

                if (buffer.Length > 0)
                {
                    buffer.Remove(buffer.Length - 1, 1);
                }
                if (configuration.AppSettings.Settings[entry.Key] == null)
                {
                    configuration.AppSettings.Settings.Add(entry.Key, buffer.ToString());
                }
                else
                {
                    configuration.AppSettings.Settings[entry.Key].Value = buffer.ToString();
                }
            }

            configuration.Save(ConfigurationSaveMode.Modified);

            #region Update SharePoint Version

            //We do this here because after the configuration save we are sure that the config file exists.
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(configuration.FilePath);
          
            XmlNode configurationNode = xmlDocument.SelectSingleNode("configuration");
            XmlNode runtimeNode = configurationNode.SelectSingleNode("runtime");

            if (comboBoxSharePointVersion.Text == Constants.DefaultSharePointVersion)
            {
                //Microsoft SharePoint 2010
                if (runtimeNode != null)
                {
                    configurationNode.RemoveChild(runtimeNode);
                }
            }
            else
            {
                //Microsoft SharePoint 2007
                if (runtimeNode == null)
                {
                    configurationNode.InnerXml += Properties.Resources.BindingRedirect;
                }
            }
                
            xmlDocument.Save(configuration.FilePath);

            #endregion

            try
            {
                ConfigurationManager.RefreshSection(configuration.AppSettings.SectionInformation.Name);
            }
            catch
            {
                throw;
            }
            
            #endregion

            if (suggestRestart)
            {
                MessageBox.Show("You changed the version of Microsoft SharePoint, in order to use this version you should restart this application.", "Important", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            this.Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void OptionsForm_Load(object sender, EventArgs e)
        {
            comboBoxSharePointVersion.Text = ConfigurationHelper.SharePointVersion;
            textBoxInetPubPath.Text = ConfigurationHelper.InetPubPath;
            textBoxCodeGenerationNamespace.Text = ConfigurationHelper.CodeGenerationNamespace;
            textBoxDefaultOwner.Text = ConfigurationHelper.DefaultOwner;
            foreach (string node in ConfigurationHelper.AutoLookupNodesToIgnore)
            {
                textBoxAutoLookupNodesToIgnore.Text += node + Environment.NewLine;
            }
            if (textBoxAutoLookupNodesToIgnore.Text.Length > 0)
            {
                textBoxAutoLookupNodesToIgnore.Text = textBoxAutoLookupNodesToIgnore.Text.Remove(textBoxAutoLookupNodesToIgnore.Text.Length - 1);
            }
            foreach (string node in ConfigurationHelper.FrequentlyUsedNodeNames)
            {
                textBoxFrequentlyUsedNodeNames.Text += node + Environment.NewLine;
            }
            if (textBoxFrequentlyUsedNodeNames.Text.Length > 0)
            {
                textBoxFrequentlyUsedNodeNames.Text = textBoxFrequentlyUsedNodeNames.Text.Remove(textBoxFrequentlyUsedNodeNames.Text.Length - 1);
            }
            foreach (string node in ConfigurationHelper.DifferentiatingAttributeNames)
            {
                textBoxAttributeNames.Text += node + Environment.NewLine;
            }
            if (textBoxAttributeNames.Text.Length > 0)
            {
                textBoxAttributeNames.Text = textBoxAttributeNames.Text.Remove(textBoxAttributeNames.Text.Length - 1);
            }
        }
    }
}
